#include "directory.h"

int create_directory(const char *path, mode_t mode){
    int ret = mkdir(path, mode);
    CREATE_DIR_CHECK(ret, path);
    printf("创建目录成功: %s  权限:%o\n",path, mode);
    return 0;
}

int create_directory_recursive(const char *path, mode_t mode) {
    char *path_copy = strdup(path);
    char *p = path_copy;

    // 创建路径中的所有目录
    while (*p != '\0') {
        if (*p == '/') {
            *p = '\0'; // 临时截断路径
            if (strlen(path_copy) > 0) {
                // 如果目录不存在则创建
                if (access(path_copy, F_OK) != 0) {
                    int ret = mkdir(path_copy, mode);
                    CREATE_DIR_CHECK(ret, path_copy);
                }
            }
            *p = '/'; // 恢复斜杠
        }
        p++;
    }

    // 创建最终的目录
    if (access(path_copy, F_OK) != 0) {
        int ret = mkdir(path_copy, mode);
        CREATE_DIR_CHECK(ret, path_copy);
    }

    free(path_copy);
    printf("递归创建目录成功: %s 权限: %o\n", path, mode);
    return 0;
}

int remove_directory(const char *path){
    int ret = rmdir(path);
    REMOVE_DIR_CHECK(ret, path);
    
    printf("删除目录成功: %s\n",path);
    return 0;
}

int remove_directory_recursive(const char *path) {
    DIR *dir = opendir(path);
    if (!dir) {
        // 如果不是目录，尝试删除文件
        if (errno == ENOTDIR) {
            int ret = unlink(path);
            REMOVE_DIR_CHECK(ret, path);
            printf("删除文件成功: %s\n", path);
            return 0;
        }
        REMOVE_DIR_CHECK(-1, path);
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        char subpath[1024];
        snprintf(subpath, sizeof(subpath), "%s/%s", path, entry->d_name);

        struct stat statbuf;
        if (lstat(subpath, &statbuf) == -1) {
            closedir(dir);
            REMOVE_DIR_CHECK(-1, subpath);
        }

        if (S_ISDIR(statbuf.st_mode)) {
            // 递归删除子目录
            remove_directory_recursive(subpath);
        } else {
            // 删除文件
            int ret = unlink(subpath);
            REMOVE_DIR_CHECK(ret, subpath);
        }
    }

    closedir(dir);

    // 删除空目录
    int ret = rmdir(path);
    REMOVE_DIR_CHECK(ret, path);
    printf("递归删除目录成功: %s\n", path);
    return 0;
}
